package com.yj.agent.util;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.io.Serializable;

public class Message<T> implements Serializable {

    private static final long serialVersionUID = -6222856254564279708L;

    private int code;
    private String message;
    private T body;

    public Message error(String msg){
        this.code = -1;
        this.message = msg;
        this.body = null;
        return this;
    }

    public Message error(String msg,int code){
        this.code = code;
        this.message = msg;
        this.body = null;
        return this;
    }

    public Message success(T body){
        this.code = 0;
        this.message = "操作成功";
        this.body = body;
        return this;
    }

    public boolean isSuccess(){
        return this.code==0?true:false;
    }

    public Message<T> bindError(BindingResult result) {
        if(result.hasErrors()) {
            this.code = Integer.valueOf(-1);
            this.message = ((ObjectError)result.getAllErrors().get(0)).getDefaultMessage();
        }
        return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getBody() {
        return body;
    }

    public void setBody(T body) {
        this.body = body;
    }
}
